<?php

namespace app\controllers\admin\uni\order;

use app\award\Award;
use app\commission\CommissionNew;
use app\commission\PaidFinish;
use app\models\order\Order;
use app\models\order\Order as Model;
use app\models\order\OrderItem;
use app\models\order\OrderOffline;
use app\models\product\Product;
use app\models\Queue;
use app\models\system\SetExpressCompany;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserRefund;
use app\models\UserBalance;
use app\models\ZRegion;
use app\services\Chain;

/**
 * Class ProductController
 * @package app\controllers\admin
 */
class OrderController extends BaseController
{
    // 重新计算佣金
    public function actionResetCommission()
    {
        $id = $this->post('id');

        try {
            $commission = UserCommission::find()
                ->where(['order_id' => $id])
                ->all();
            if (!empty($commission)) {
                foreach ($commission as $c) {

                    // 如果是累计业绩奖, 则跳过
                    // if ($c->award_type == 101) {
                    //     continue;
                    // }

                    $account = UserAccount::findOne(['user_id' => $c->user_id]);
                    if ($c->status == 1) {

                        // return $this->fail('订单已经完成,不能重新计算');

                        // balance logs
                        UserBalance::addLog($c->user_id,
                            $account->balance, -$c->balance, $account->balance - $c->balance, '重算佣金', $c->order_id);

                        $account->balance -= $c->balance;
                    }

                    if ($c->status == 0) {
                        $account->await_balance -= $c->balance;
                    }

                    $account->save();

                    $c->delete();
                }

            }

            // 队列中的也要删除
            // Queue::updateAll(['status' => -1], ['order_id' => $id]);

            $order = Order::findOne(['id' => $id]);

            // 记录重算日志
            $order->reset_log = json_encode(Chain::getReferrerChain($order->user_id));
            $order->save();

            new Award($order);

            return $this->success();

        } catch (\Exception $e) {
            var_dump($e->getFile());
            var_dump($e->getLine());
            var_dump($e->getMessage());
        }
    }

    public function actionList()
    {
        $sn = $this->post('sn');
        $id = $this->post('id');

        $status = $this->post('status');
        $store = $this->post('store', 0);
        $product = $this->post('product');

        $export = $this->post('export');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        // user
        $user_id = $this->post('user_id');
        $mobile = $this->post('mobile');

        // date
        $start = $this->post('start');
        $end = $this->post('end');

        $type = $this->post('type', -1);

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']]);
            // no group
            // ->andWhere(['is_group' => 0]);

        if ($type > -1) {
            $query->andWhere(['is_group' => $type]);
        }

        // product
        if ($product) {
            $product_ids = Product::find()
                ->where(['like', 'title', $product])
                ->select(['id'])
                ->column();
            // if ($product_ids) {
            //     $order_ids = OrderItem::find()
            //         ->where(['product_id' => $product_ids])
            //         ->select(['order_id'])
            //         ->column();
            //     if ($order_ids) {
            //         $query->andWhere(['id' => $order_ids]);
            //     }
            // }
            $order_ids = OrderItem::find()
                ->where(['product_id' => $product_ids])
                ->select(['order_id'])
                ->column();
            // var_dump($product_ids, $order_ids);exit;

            $query->andWhere(['id' => $order_ids]);
        }

        // if ($start) {
        //     $query->andWhere(['>=', 'create_time', $start]);
        // }
        // if ($end) {
        //     $query->andWhere(['<=', 'create_time', $end]);
        // }
        if ($start) {
            // $query->andWhere(['>=', 'create_time', $start]);
            $query->andWhere(['>=', 'DATE_FORMAT(create_time, "%Y-%m-%d")', date('Y-m-d', strtotime($start))]);
        }
        if ($end) {
            // $query->andWhere(['<=', 'create_time', $end]);
            $query->andWhere(['<=', 'DATE_FORMAT(create_time, "%Y-%m-%d")', date('Y-m-d', strtotime($end))]);
        }

        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }

        if ($mobile) {
            $ids = User::find()
                ->where(['like', 'mobile', $mobile])
                ->select(['id'])
                ->asArray()
                ->column();
            $query->andWhere(['user_id' => $ids]);
        }

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
        } else {
            $query->orderBy(['id' => SORT_DESC]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($sn) {
            $query->andWhere(['like', 'sn', $sn]);
        }
        // if ($type > -1) {
        //     $query->andWhere(['is_group' => $type]);
        // }

        // 云仓提货类型
        if ($store == 1) {
            $query->andWhere(['>', 'is_extract', 0]);
        }
        if ($store == 2) {
            $query->andWhere(['is_extract' => 0]);
        }

        // var_dump($query->createCommand()->getRawSql());exit;

        $with = [
            'item', 'item.product',
            'address', 'address.city',
            'user',
            'commission',
            'supplier',
        ];

        // export
        if ($export) {
            $list = $query->with($with)->asArray()->all();
            foreach ($list as &$item) {

                // var_dump($item);exit;

                if ($item['is_store']) {
                    continue;
                }

                if (!$item['address']) {
                    continue;
                }

                $item['user']['nickname'] = base64_decode($item['user']['nickname']);
                $item['address']['nickname'] = base64_decode($item['address']['nickname']);

                // var_dump($item['address']);exit;

                $item['address']['city'] = [
                    'province' => ZRegion::find()->where(['code' => $item['address']['province_id']])->select(['name'])->scalar(),
                    // 'province_id' => $model['province_id'],
                    'city' => ZRegion::find()->where(['code' => $item['address']['city_id']])->select(['name'])->scalar(),
                    // 'city_id' => $model['city_id'],
                    'area' => ZRegion::find()->where(['code' => $item['address']['area_id']])->select(['name'])->scalar(),
                    // 'area_id' => $model['area_id'],
                ];
            }
            return $this->success(
                $list
            );
        }


        // $query->with($with);
        // var_dump($query->createCommand()->getRawSql());exit;

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->with($with)
            ->asArray()
            ->all();

        // 打款凭证
        foreach ($list as &$item) {
            if ($item['pay_type'] == -88) {
                $images = OrderOffline::find()
                    ->where(['order_id' => $item['id']])
                    ->with(['image'])
                    ->asArray()
                    ->all();
                $i = [];
                foreach ($images as $image) {
                    if ($image['image']['path']) {
                        array_push($i, $image['image']['path']);
                    }
                }
                $item['offline'] = $i;
            }
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionView()
    {
        $id = $this->post('id');

        // order
        $model = Model::find()
            ->where(['id' => $id])
            ->with([
                'item', 'item.product', 'item.product.mainImage',
                'item.logistics', 'item.logistics.company', 'item.logistics.address', 'item.logistics.address.city',
                'address', 'address.city',
                'user',
                'commission', 'commission.user',
                'supplier'
            ])
            ->asArray()
            ->one();

        if (!$model['user']) {
            return $this->fail('会员数据已经被清除了, 可能调整了数据库');
        }

        $model['user']['nickname'] = base64_decode($model['user']['nickname']);
        // $model['address']['nickname'] = base64_decode($model['address']['nickname']);

        if ($model['user']['base64Image']) {
            $model['user']['avatar'] = $model['user']['base64Image'];
        }

        // var_dump($model['address']);exit;

        if ($model['address']) {
            $model['address']['nickname'] = base64_decode($model['address']['nickname']);
            $model['address']['city'] = [
                'province' => ZRegion::find()->where(['code' => $model['address']['province_id']])->select(['name'])->scalar(),
                // 'province_id' => $model['province_id'],
                'city' => ZRegion::find()->where(['code' => $model['address']['city_id']])->select(['name'])->scalar(),
                // 'city_id' => $model['city_id'],
                'area' => ZRegion::find()->where(['code' => $model['address']['area_id']])->select(['name'])->scalar(),
                // 'area_id' => $model['area_id'],
            ];
        }

        // 佣金昵称
        if ($model['commission']) {
            foreach ($model['commission'] as &$c) {
                if ($c['user']['nickname']) {
                    $c['user']['nickname'] = base64_decode($c['user']['nickname']);
                }
            }
        }

        // logistics
        $logistics = SetExpressCompany::find()
            ->orderBy(['id' => SORT_ASC])
            ->asArray()
            ->all();

        // 日志
        if ($model['log']) {
            $model['log'] = json_decode($model['log']);
        }
        if ($model['reset_log']) {
            $model['reset_log'] = json_decode($model['reset_log']);
        }

        if ($model) {
            return $this->success([
                'order' => $model,
                'logistics' => $logistics
            ]);
        }

        return $this->fail('不存在该订单');
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    // offline
    public function actionOfflineOk()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id]);
        if (!$model) {
            return $this->fail('不存在该订单');
        }
        if ($model->offline_ok == 1) {
            return $this->fail('请勿重复操作');
        }

        $model->offline_ok = 1;
        $model->save();

        PaidFinish::order($model);

        return $this->success();
    }

    // refund
    public function actionRefund()
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $id = $this->post('id');
            $model = Model::findOne(['id' => $id]);
            if ($model) {
                $commission = UserCommission::find()
                    ->where(['order_id' => $model->id])
                    ->all();

                // 退余额
                if ($model->status == 1 || $model->status == 2 || $model->status == 3) {
                    $total_pay = $model->use_balance + $model->use_money;
                } else if ($model->status == 0) {
                    $total_pay = $model->use_balance;
                } else {
                    $total_pay = 0;
                }
                $account = UserAccount::findOne(['user_id' => $model->user_id]);
                $account->balance += $total_pay;
                $account->save();

                // 退佣金
                $commission_ids = [];
                foreach ($commission as $c) {

                    // 如果存在已经返佣到帐了, 则不能退货
                    if ($c->status == 1) {
                        return $this->fail('返佣已经到帐,不能退款,请线下处理!');
                    }

                    $a = UserAccount::findOne(['user_id' => $c->user_id]);

                    if ($c->status == 0) {
                        $a->await_balance -= $c->balance;
                    } else if ($c->status == 1) {
                        $a->balance -= $c->balance;
                    }

                    $a->save();

                    // $c->status = -1;
                    // $c->save();

                    // 直接删除, 记录下佣金
                    array_push($commission_ids, json_encode($c->toArray()));
                    $c->delete();
                }

                // 订单状态
                $model->status = Order::$statusMapping['REFUND'];
                $model->save();

                // 退款记录
                $refund = new UserRefund();
                $refund->order_id = $model->id;
                $refund->commission_ids = json_encode($commission_ids);
                $refund->save();

                // 队列中的也要删除
                Queue::updateAll(['status' => -1], ['order_id' => $model->id]);
            }

            $transaction->commit();
            return  $this->success();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }
    }

    // 指定谁下的单
    public function actionDebug()
    {
        $id = $this->post('id');
        $user_id = $this->post('user_id');

        $order = Order::findOne(['id' => $id]);
        if ($order) {
            $order->user_id = $user_id;
            $order->save();

            // OrderItem::updateAll(['user_id' => $user_id], ['order_id' => $id]);

            return $this->success();
        }
    }
}